<template>
  <main>
    <p id="no-item">暂无数据。</p>
    <div id="items">
      <div 
        v-for="(item, index) in state.items"
        :key="item.id"
        class="read-item"
        :class="{selected: index === currentIndex}"
        @click="changeIndex(index)"
        @dblclick="openWebSite(item.url)"
      >
        <img :src="item.screenshot" alt="item.title">
        <h2>{{item.title}}</h2>
      </div>
    </div>
  </main>
</template>

<script>
import { reactive, wat, watchEffect } from 'vue'
import { useStore } from 'vuex'

import useIndex from './hooks/useIndex'
import useOpenWindow from './hooks/useOpenWindow'

export default {
  setup() {
    const { state: vuexState, getters, commit } = useStore()
    const { ipcRenderer } = global.electron
    const { currentIndex, changeIndex } = useIndex()
    const { openWebSite } = useOpenWindow()

    let state = reactive({
      items: vuexState.items
    })

    const _saveItems = (items) => {
      // delete item.screenshot
      // const cookie = { url: 'https://www.readit.com.cn', name: JSON.stringify(item.id), value: JSON.stringify(item) }
      // global.session.defaultSession.cookies.set(cookie)
      //   .then(() => {
      //     // success
      //   }, (error) => {
      //     // console.error(error)
      //   })

      //   global.session.defaultSession.cookies.get({})
      //   .then((cookies) => {
      //     console.log(cookies)
      //   }).catch((error) => {
      //     console.log(error)
      //   })

      localStorage.setItem('readit-items', JSON.stringify(items))
    }

    watchEffect(() => {
      state.items = getters.filteredItems
      _saveItems(state.items)
    })

    ipcRenderer.on('new-item', (e, args) => {
      const item = {
        id: new Date().getTime(),
        ...args
      }

      // const items = JSON.parse(localStorage.getItem('readit-items')) || []
      // items.push(item)

      commit('setItems', item)

      commit('setIsLoading', false)
      commit('setIsOpen', false)
    })

    return {
      state,
      currentIndex,
      changeIndex,
      openWebSite
    }
  }
}
</script>

<style lang='scss' scoped>
#items {
  flex-grow: 1;
}

#no-item {
  font-weight: bold;
  color: silver;
  text-align: center;
  width: 100%;
  position: absolute;
  top: 100px;
  z-index: -1;
}

.read-item {
  display: flex;
  align-items: center;
  align-content: center;
  border-bottom: lightgray 2px solid;
  background: #fafafa;
  padding: 10px;
  border-left: 10px solid lightgray;
  -webkit-user-select: none;
  img {
    width: 20%;
    margin-right: 25px;
    border: solid 1px #ccc;
  }
  &:hover {
    background: #eee
  }
  &.selected {
    border-left-color: dodgerblue
  }
}
</style>